from report import report_sxw
from report.report_sxw import rml_parse
from osv import fields, osv
import time
import re
import datetime
from dateutil.relativedelta import relativedelta
import pooler
from operator import itemgetter


class Parser(report_sxw.rml_parse):
    def __init__(self, cr, uid, name, context):
        super(Parser, self).__init__(cr, uid, name, context)
        self.localcontext.update({
            'get_lines': self.get_lines,
        })
        self.context = context


    def get_lines(self, o):
        cr = self.cr
        uid = self.uid
        result = []
        product_obj = self.pool.get('product.product')
        categ_obj = self.pool.get('product.category')
        condition = [('sale_ok', '=', True)]
        if o['categ_id']:
            lst_categ = categ_obj.search(cr, uid, [('parent_id', 'child_of', o['categ_id'])])
            condition += [('categ_id', 'in', lst_categ)]
        lst_product = product_obj.search(cr, uid, condition, order='default_code')

        to_date = datetime.datetime.strptime(o['date'], '%Y-%m-%d')
        to_date += datetime.timedelta(days=1)
        ctx = {
            'to_date': to_date
        }
        if o['location_id']:
            ctx = {
                'location': o['location_id'],
                'to_date': to_date
            }
        for product in product_obj.browse(cr, uid, lst_product, ctx):
            res = {
                'name': product.name or '',
                'code': product.default_code or '',
                'cate': product.categ_id.name or '',
                'real': product.qty_available,
                'virtual': product.virtual_available,
            }
            result.append(res)
        return result   
    
      
    
